/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.utils;

import java.util.concurrent.*;

public class ThreadPool implements IThreadPool {
	
	private ThreadPoolExecutor executor;
	private final int DEFAULT_KEEP_ALIVE_TIME_MSEC = 50;
	private final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
	
	private class PoolThreadFactory implements ThreadFactory {

		private String threadId;
		private int count = 0;

		PoolThreadFactory(String threadId) {
			this.threadId = threadId;
		}
		
		@Override
		public Thread newThread(Runnable r) {
			Thread result = new Thread(r, this.threadId+"/"+count++);
			result.setDaemon(true);
			return result;
		}
		
	}
	
	public ThreadPool(int initialThreadsCnt, int maxThreadsCnt, String threadPoolId) {
		this.executor = new ThreadPoolExecutor (
			initialThreadsCnt, 
			maxThreadsCnt, 
			DEFAULT_KEEP_ALIVE_TIME_MSEC, 
			TimeUnit.MILLISECONDS,
			queue,
			new PoolThreadFactory(threadPoolId)
		);		
	}
	
	@Override
	public void execute(Runnable task) {
		this.executor.submit(task);
		// this.executor.execute(task);
		// task.run();
	}
	
	@Override
	public void destroy() {
		if(executor!=null) {
			executor.shutdown();
			executor = null;
		}
	}
	
	public void finalize() {
		destroy();
	}

}
